<template>
  <div class="notes">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>学习笔记</h2>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索笔记"
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新建笔记
            </el-button>
          </div>
        </div>
      </template>

      <!-- 笔记列表 -->
      <div class="note-list">
        <el-row :gutter="20">
          <el-col 
            v-for="note in noteList" 
            :key="note.id" 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
          >
            <el-card 
              class="note-card" 
              shadow="hover"
              @click="handleEdit(note)"
            >
              <template #header>
                <div class="note-header">
                  <h3 class="note-title">{{ note.title }}</h3>
                  <el-dropdown trigger="click" @command="(command) => handleCommand(command, note)">
                    <el-button type="primary" link>
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="edit">编辑</el-dropdown-item>
                        <el-dropdown-item command="share">分享</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
              <div class="note-content">
                <p class="note-text">{{ note.content }}</p>
                <div class="note-meta">
                  <span class="note-course">
                    <el-icon><Reading /></el-icon>
                    {{ note.courseName }}
                  </span>
                  <span class="note-time">
                    <el-icon><Timer /></el-icon>
                    {{ note.updateTime }}
                  </span>
                </div>
                <div class="note-tags">
                  <el-tag
                    v-for="tag in note.tags"
                    :key="tag"
                    size="small"
                    class="note-tag"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑笔记对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建笔记' : '编辑笔记'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="选择课程">
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入笔记内容"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-tag
            v-for="tag in form.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="tagInputRef"
            v-model="inputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >
            + 新标签
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { 
  Search, 
  Plus, 
  More, 
  Reading, 
  Timer 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索
const searchQuery = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 笔记列表
const noteList = ref([])

// 课程选项
const courseOptions = ref([
  { id: 1, name: '课程1' },
  { id: 2, name: '课程2' },
  { id: 3, name: '课程3' }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: null,
  title: '',
  courseId: '',
  content: '',
  tags: []
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const tagInputRef = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入笔记标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入笔记内容', trigger: 'blur' }
  ]
}

// 获取笔记列表
const fetchNoteList = async () => {
  try {
    // TODO: 调用API获取笔记列表
    // 优先从 localStorage 中读取数据
    const savedNotes = localStorage.getItem('userNotes'); // 从localStorage读取笔记数据
    let mockData;
    
    if (savedNotes) {
      mockData = JSON.parse(savedNotes);
    } else {
      // 这里模拟数据
      mockData = Array.from({ length: 20 }, (_, index) => ({
        id: index + 1,
        title: `笔记${index + 1}`,
        content: `这是笔记${index + 1}的内容，包含了一些重要的学习要点...`,
        courseName: `课程${index % 3 + 1}`,
        updateTime: new Date().toLocaleString(), // 初始化时设置当前时间
        tags: ['重要', '难点', '复习']
      }))
       // 首次加载时保存到 localStorage
      localStorage.setItem('userNotes', JSON.stringify(mockData));
    }

    // 模拟搜索
    let filteredData = mockData
    if (searchQuery.value) {
      filteredData = mockData.filter(note => 
        note.title.includes(searchQuery.value) ||
        note.content.includes(searchQuery.value)
      )
    }
    
    total.value = filteredData.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    noteList.value = filteredData.slice(start, end)
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    ElMessage.error('获取笔记列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchNoteList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchNoteList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchNoteList()
}

// 新建笔记
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    id: null,
    title: '',
    courseId: '',
    content: '',
    tags: []
  })
  dialogVisible.value = true
}

// 编辑笔记
const handleEdit = (note) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: note.id,
    title: note.title,
    courseId: courseOptions.value.find(c => c.name === note.courseName)?.id,
    content: note.content,
    tags: [...note.tags]
  })
  dialogVisible.value = true
}

// 处理下拉菜单命令
const handleCommand = async (command, note) => {
  switch (command) {
    case 'edit':
      handleEdit(note)
      break
    case 'share':
      // TODO: 实现分享功能
      ElMessage.success('分享功能开发中')
      break
    case 'delete':
      try {
        await ElMessageBox.confirm(
          '确定要删除该笔记吗？此操作不可恢复！',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        // TODO: 调用API删除笔记
        const index = noteList.value.findIndex(item => item.id === note.id)
        if (index > -1) {
          noteList.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}

// 处理标签输入确认
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (!form.tags.includes(inputValue.value)) {
      form.tags.push(inputValue.value)
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 移除标签
const handleRemoveTag = (tag) => {
  form.tags.splice(form.tags.indexOf(tag), 1)
}

// 提交表单（新建或编辑笔记）
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    const now = new Date();
    const updateTime = `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

    const savedNotes = localStorage.getItem('userNotes');
    let notes = savedNotes ? JSON.parse(savedNotes) : [];

    if (dialogType.value === 'add') {
      // 新建笔记
      const newNote = {
        id: Date.now(), // 使用时间戳作为唯一ID
        ...form,
        courseName: courseOptions.value.find(c => c.id === form.courseId)?.name || '未知课程', // 根据courseId查找课程名称
        updateTime: updateTime // 设置创建时间
      };
      notes.push(newNote);
      ElMessage.success('笔记创建成功');
    } else {
      // 编辑笔记
      const index = notes.findIndex(note => note.id === form.id);
      if (index !== -1) {
        notes[index] = {
          ...notes[index], // 保留原有属性
          title: form.title,
          courseId: form.courseId,
          courseName: courseOptions.value.find(c => c.id === form.courseId)?.name || '未知课程', // 更新课程名称
          content: form.content,
          tags: form.tags,
          updateTime: updateTime // 更新修改时间
        };
        ElMessage.success('笔记更新成功');
      } else {
        ElMessage.error('未找到要编辑的笔记');
      }
    }

    // 保存更新后的笔记列表到 localStorage
    localStorage.setItem('userNotes', JSON.stringify(notes));

    // 重新获取并显示笔记列表，以便更新UI
    fetchNoteList();

    dialogVisible.value = false;
  } catch (error) {
    console.error('提交表单失败:', error);
    ElMessage.error('请检查表单填写是否正确');
  }
};

onMounted(() => {
  fetchNoteList()
})
</script>

<style scoped>
.notes {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.note-list {
  margin-top: 20px;
}

.note-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.note-card:hover {
  transform: translateY(-5px);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.note-title {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.note-content {
  padding: 10px 0;
}

.note-text {
  margin: 0 0 15px;
  color: var(--el-text-color-regular);
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.note-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.note-course,
.note-time {
  display: flex;
  align-items: center;
  gap: 5px;
}

.note-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.note-tag {
  margin-right: 5px;
}

.tag-input {
  width: 100px;
  margin-left: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 